import os
import pymysql
import requests
from commons import request_data
from commons.request_data import ECU_TEST_ACCOUNT
from utils.yaml_utils import write_yaml, read_yaml, clean_yaml


# 1. 数据库操作
class DBUtils:
    def __init__(self):
        self.host = request_data.DATABASE_CONFIG["ecu_test_mysql"]['host']
        self.port = request_data.DATABASE_CONFIG["ecu_test_mysql"]['port']
        self.user = request_data.DATABASE_CONFIG["ecu_test_mysql"]['user']
        self.password = request_data.DATABASE_CONFIG["ecu_test_mysql"]['password']
        self.db = request_data.DATABASE_CONFIG["ecu_test_mysql"]['db']

    def conn_db(self, sql):
        """
        功能：实现数据库连接，sql执行
        :param sql: 执行的sql
        :return:
        """
        db = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.db )
        cursor = db.cursor()
        cursor.execute(sql)
        data = cursor.fetchall()
        db.commit()
        db.close()
        cursor.close()
        return data

    def get_sso_password(self, env, user_name=ECU_TEST_ACCOUNT[0]):
        """
        功能：获取用户密码
        :param env: 环境
        :return:
        """
        sql = ("""
                SELECT * FROM test_iot.ecu_test_account WHERE `user_name` ='{}' and `env` = '{}';
               """).format(user_name, env)
        data = self.conn_db(sql)[0][4]
        return data

    def get_token(self, env):
        """
        功能：获取用户token
        :param env: 环境
        :return:
        """
        sql = "SELECT * FROM test_iot.name_value where name = '{}_token'".format(env)
        data = self.conn_db(sql)[0][-1]
        return data

    def update_token(self, env):
        """
        功能：不同ip登录后需要更新token; 好像没什么用
        """
        url = ""
        if env == "online":
            url = "https://sso.songguo7.com/sso/login"
        elif env == "test":
            url = "http://test-sso-in.songguo7.com/sso/login"
        params = {
            "params": {
                "login_name": ECU_TEST_ACCOUNT[0],
                "password": self.get_sso_password(env),
            }
        }
        res = requests.post(url, json=params)
        cookies = res.json()["data"]["access_token"]
        cookies_new = f"sandbox_access_token={cookies}; access_token={cookies}"
        sql = '''
            UPDATE test_iot.name_value SET value='{}' WHERE name='test_token';
            '''.format(cookies_new)
        # print("更新的sql" + sql)
        self.conn_db(sql)
        return cookies

    def get_cookie(self, env):
        if env == "test":
            self.url = "http://test-sso-in.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "e590ab8e56e8133aa5fb99e3f2ec9d4adad509fe"
                }
            }
        elif env == "online":
            self.url = "https://sso.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "8197548f01ba4da1881ce3a8c76a24d1b7a381be"
                }
            }

    def get_headers(self, env):
        headers = {
            "X-AUTH-SOURCE": "SSO",
            "Cookie": DBUtils().get_token(env),
            "Content-Type": "application/json; charset=UTF-8",
            'Connection': 'close'
        }
        return headers

    def update_headers(self, env):
        self.update_token(env)
        headers = {
            "X-AUTH-SOURCE": "SSO",
            "Cookie": self.get_token(env),
            "Content-Type": "application/json; charset=UTF-8",
            'Connection': 'close'
        }
        return headers

    def get_req_params(self, params, ecu):
        params = {
            "params": {
                "steStr": ecu,
                "channel_type": "NET",
                "command_type": "331",
                "need_ack": False,
                "ste_sns": [
                    ecu
                ],
                "tenant_code": "1",
                "param": params
            }
        }
        return params


class RequestUtils:
    def __init__(self):
        self.session = requests.Session()

    def all_request(self, **kwargs):
        """
        功能：获取用户session  pending。。。
        :param kwargs: 请求参数
        :return:
        """
        response = self.session.request(**kwargs)
        # print(response.text)
        return response


if __name__ == '__main__':
    # env = "test"
    sql = '''select * from ebike_galaxy.bike_bind order by id desc limit 5'''
    print(DBUtils().update_headers("test"))
